# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QFrame, QVBoxLayout
from qfluentwidgets import BodyLabel, setFont, FluentIcon, SegmentedWidget, SingleDirectionScrollArea

from common.server import VideoModel
from components import Alert, SlidingStackedWidget
from .task_view import DownloadingTaskView, SuccessTaskView


class DownloadInterface(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.titleLabel = BodyLabel('下载管理', self)
        self.pivot = SegmentedWidget(self)
        self.stackedWidget = SlidingStackedWidget(self)
        self.downloadingTaskView = DownloadingTaskView(self)
        self.successTaskView = SuccessTaskView(self)

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName("DownloadInterface")
        setFont(self.titleLabel, 26)
        self.titleLabel.setFixedHeight(80)

        self.pivot.addItem("downloading", '正在下载', icon=FluentIcon.SYNC)
        self.pivot.addItem("finished", '已完成', icon=FluentIcon.COMPLETED)
        self.pivot.setCurrentItem("downloading")

        self.stackedWidget.addWidget(self.downloadingTaskView)
        self.stackedWidget.addWidget(self.successTaskView)

        self.__initLayout()
        self.__connectSignals()

    def __initLayout(self):
        vertical_layout = QVBoxLayout(self)
        vertical_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        vertical_layout.setContentsMargins(30, 11, 30, 11)
        vertical_layout.addWidget(self.titleLabel)
        vertical_layout.addWidget(self.pivot)

        scrollArea = SingleDirectionScrollArea(self)
        scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        scrollArea.setWidget(self.stackedWidget)
        self.stackedWidget.setAutoFillBackground(False)
        scrollArea.setWidgetResizable(True)
        scrollArea.enableTransparentBackground()
        vertical_layout.addWidget(scrollArea, 1)

    def __connectSignals(self):
        self.pivot.currentItemChanged.connect(self.onPivotChanged)

        self.downloadingTaskView.finished.connect(self.successTaskView.addTask)

    def onPivotChanged(self, routeKey: str):
        items = {
            "downloading": self.downloadingTaskView,
            "finished": self.successTaskView,
        }
        self.stackedWidget.setCurrentWidget(items[routeKey])
